<?php

require_once("includes/pagetop.php");
if(!isset($_SESSION['Allyfolio_User_ID']))
{
    redirect("index.php");
}
$montharr=array();
$montharr['jan']=1;
$montharr['feb']=2;
$montharr['mar']=3;
$montharr['apr']=4;
$montharr['may']=5;
$montharr['jun']=6;
$montharr['jul']=7;
$montharr['aug']=8;
$montharr['sep']=9;
$montharr['oct']=10;
$montharr['nov']=11;
$montharr['dec']=12;

$blockfriendslist=$pdodbobj->fetch_array($pdodbobj->query("select to_user_id from af_events_settings where user_id=".$_SESSION['Allyfolio_User_ID']));
$blockfriendslist1=$pdodbobj->fetch_array($pdodbobj->query("select user_id from af_events_settings where to_user_id=".$_SESSION['Allyfolio_User_ID']));

$blockedusers=array();

for($i=0;$i<count($blockfriendslist);$i++)
{
    if(!in_array($blockfriendslist[$i]['to_user_id'],$blockedusers))
    {
        $blockedusers[]=$blockfriendslist[$i]['to_user_id'];
    }
}

for($i=0;$i<count($blockfriendslist1);$i++)
{
    if(!in_array($blockfriendslist1[$i]['user_id'],$blockedusers))
    {
        $blockedusers[]=$blockfriendslist1[$i]['user_id'];
    }
}

if(isset($_POST['actiontype']) && $_POST['actiontype']=="SaveEvent")
{
    
    $eventarr=$_POST['Event'];
    
    $eventarr['Event_Date']=returnDateTimestamp($eventarr['Event_Date']);
    $eventarr['Friends_ID']=str_ireplace("[","",$eventarr['Friends_ID']);
    $eventarr['Friends_ID']=str_ireplace("]","",$eventarr['Friends_ID']);
    $eventarr['Friends_ID']=str_ireplace('\"',"'",$eventarr['Friends_ID']);
    $eventarr['Friends_ID']=str_ireplace('"',"'",$eventarr['Friends_ID']);
    $eventarr['Friends_ID']=str_ireplace("'","",$eventarr['Friends_ID']);
    
    if($eventarr['Privacy_Type_ID']==2 || $eventarr['Privacy_Type_ID']==1)
    {
        $eventarr['Friends_ID']="";
        $eventarr['Cluster_ID']="0";
    }
    
    if($eventarr['Privacy_Type_ID']==3)
    {
        $eventarr['Guest_Invite']=0;
        $eventarr['Cluster_ID']=0;
        
        $friendidarr=$eventarr['Friends_ID'];
        $friendsstr=implode("','",$friendidarr);
        
        $eventarr['Friends_ID']="'".$friendsstr."'";
    }
    
    if($eventarr['Privacy_Type_ID']==4)
    {
        $eventarr['Friends_ID']="";
        $eventarr['Guest_Invite']=0;
    }
    
    $eventarr['Last_Modified_By']=$_SESSION['Allyfolio_User_ID'];
    $eventarr['Modified_Date']=time();
    
    $lastprivacy=0;
    
    if(isset($_POST['event_id']) && $_POST['event_id']!='')
    {
        $eventoldinfo=$pdodbobj->fetch_array($pdodbobj->query("select * from af_events where Event_ID=:evtid",array("evtid"=>$_POST['event_id'])));
        $lastprivacy=$eventoldinfo[0]['Privacy_Type_ID'];
        $pdodbobj->updateData("af_events",$eventarr,array("Event_ID"=>base64_decode($_POST['event_id'])));
        $lasteventid=base64_decode($_POST['event_id']);
        $action="Updat";
        $insertarr=array();
        $insertarr['Message']=$eventarr['Inbox_Message'];
        $insertarr['Message_Date']=time();
        $insertarr['To_Status']=0;
        $pdodbobj->updateData("af_user_inbox",$insertarr,array("Record_ID"=>$lasteventid));
     }
    else
    {
        $eventarr['Created_By']=$_SESSION['Allyfolio_User_ID'];
        $pdodbobj->insertData("af_events",$eventarr);
        $lasteventid=$pdodbobj->last_id();
        $action="Creat";    
        
    }
    
    if($lasteventid>0)
    {
        
        if($action!="Creat")
        {
            if($eventoldinfo[0]['Privacy_Type_ID']!=$eventarr['Privacy_Type_ID'])
            {
                $pdodbobj->deleteData("af_user_inbox",array("Record_ID"=>$lasteventid,"Module_From"=>"Event"));
            }
            else
            {
                $pdodbobj->updateData("af_user_inbox",array("Message"=>$eventarr['Inbox_Message']),array("Record_ID"=>$lasteventid,"Module_From"=>"Event"));
            }
        }
                
        if($eventarr['Privacy_Type_ID']==2 && $lastprivacy!=2)
        {
            
            
            $userinfo=$pdodbobj->fetch_array($pdodbobj->query("select Active_Friends_IDs from af_users where User_ID=:fromid",array("fromid"=>$_SESSION['Allyfolio_User_ID'])));
            if(isset($userinfo[0]['Active_Friends_IDs']) && $userinfo[0]['Active_Friends_IDs']!="")
            {
                $usersarr=explode(",",$userinfo[0]['Active_Friends_IDs']);
                for($i=0;$i<count($usersarr);$i++)
                {
                    if(!in_array($usersarr[$i],$blockedusersr))
                    {
                        $insertarr=array();
                        $insertarr['Record_ID']=$lasteventid;
                        $insertarr['Module_From']="Event";
                        $insertarr['From_User_ID']=$_SESSION['Allyfolio_User_ID'];
                        $insertarr['To_User_ID']=$usersarr[$i];
                        $insertarr['Message']=$eventarr['Inbox_Message'];
                        $insertarr['Message_Date']=time();
                        $pdodbobj->insertData("af_user_inbox",$insertarr);
                        
                        $notificationarr=array();
                        $notificationarr["Unique_ID"]=$lasteventid;
                        $notificationarr["Activity_Type_ID"]=6;
                        $notificationarr["source_User_ID"]=$_SESSION['Allyfolio_User_ID'];
                        $notificationarr["Target_User_ID"]=$usersarr[$i];
                        $notificationarr["Status"]=1;
                        $pdodbobj->insertData("af_notificationwatcher",$notificationarr);
                        
                    }
                }
            }
            
        }
        if($eventarr['Privacy_Type_ID']==3 && $lastprivacy!=3)
        {
            $friendarr=explode("','",$eventarr['Friends_ID']);
            if(count($friendarr)>0)
            {
                for($i=0;$i<count($friendarr);$i++)
                {
                    if(!in_array(str_ireplace("'","",$friendarr[$i]),$blockedusersr))
                    {
                        $insertarr=array();
                        $insertarr['Record_ID']=$lasteventid;
                        $insertarr['Module_From']="Event";
                        $insertarr['From_User_ID']=$_SESSION['Allyfolio_User_ID'];
                        $insertarr['To_User_ID']=str_ireplace("'","",$friendarr[$i]);
                        $insertarr['Message']=$eventarr['Inbox_Message'];
                        $insertarr['Message_Date']=time();
                        $pdodbobj->insertData("af_user_inbox",$insertarr);
                        
                        $notificationarr=array();
                        $notificationarr["Unique_ID"]=$lasteventid;
                        $notificationarr["Activity_Type_ID"]=6;
                        $notificationarr["source_User_ID"]=$_SESSION['Allyfolio_User_ID'];
                        $notificationarr["Target_User_ID"]=str_ireplace("'","",$friendarr[$i]);
                        $notificationarr["Status"]=1;
                        $pdodbobj->insertData("af_notificationwatcher",$notificationarr);
                    }
                }
            }
            
        }
        $friendsids="";
        if($eventarr['Privacy_Type_ID']==4 && $lastprivacy!=4)
        {
            $userinfo=$pdodbobj->fetch_array($pdodbobj->query("select Friend_ID from af_cluster_friends where Added_By_User_ID=:fromid and Cluster_ID=:clusterid",array("fromid"=>$_SESSION['Allyfolio_User_ID'],"clusterid"=>$eventarr['Cluster_ID'])));
            if(isset($userinfo[0]['Friend_ID']) && $userinfo[0]['Friend_ID']!="")
            {
                for($i=0;$i<count($userinfo);$i++)
                {
                    if($userinfo[$i]['Friend_ID']!="")
                    {
                        if(!in_array($userinfo[$i]['Friend_ID'],$blockedusersr))
                        {
                            $insertarr=array();
                            $insertarr['Record_ID']=$lasteventid;
                            $insertarr['Module_From']="Event";
                            $insertarr['From_User_ID']=$_SESSION['Allyfolio_User_ID'];
                            $insertarr['To_User_ID']=$userinfo[$i]['Friend_ID'];
                            $insertarr['Message']=$eventarr['Inbox_Message'];
                            $insertarr['Message_Date']=time();
                            $pdodbobj->insertData("af_user_inbox",$insertarr);
                            $friendsids.="'".$userinfo[$i]['Friend_ID']."',";
                            
                            $notificationarr=array();
                            $notificationarr["Unique_ID"]=$lasteventid;
                            $notificationarr["Activity_Type_ID"]=6;
                            $notificationarr["source_User_ID"]=$_SESSION['Allyfolio_User_ID'];
                            $notificationarr["Target_User_ID"]=$userinfo[$i]['Friend_ID'];
                            $notificationarr["Status"]=1;
                            $pdodbobj->insertData("af_notificationwatcher",$notificationarr);
                            
                        }
                    }
                }
                
                if($friendsids!="")
                {
                    $friendsids=substr($friendsids,0,strlen($friendsids)-1);
                    $pdodbobj->updateData("af_events",array("Friends_ID"=>$friendsids),array("Event_ID"=>$lasteventid));
                }
            }
            
        }
        
        
        $msg="Event ".$action."ed successfully";
        $msgtype="Success";
    }
    else
    {
        $msg="There is an error in ".$action."ing Event";
        $msgtype="Error";
    }
    
}

if(isset($_POST['actiontype']) && $_POST['actiontype']=="DeleteEvent" && isset($_POST['event_id']) && $_POST['event_id']!='')
{
    $conditionarr=array("Event_ID"=>base64_decode($_POST['event_id']));
    $pdodbobj->deleteData("af_user_inbox",array("Record_ID"=>base64_decode($_POST['event_id']),"Module_From"=>"Event"));
    $pdodbobj->deleteData("af_notificationwatcher",array("Unique_ID"=>base64_decode($_POST['event_id']),"Activity_Type_ID"=>6));
    $pdodbobj->deleteData("af_events",$conditionarr);
    $msg="Event Deleted successfully";
    $msgtype="Success";
}
    
function returnDateTimestamp($date)
{
    if(trim($date!=""))
    {
        $spacearr=explode(" ",$date);
        $datearr=explode("/",$spacearr[0]);
        $hourarr=explode(":",$spacearr[1]);
        if(isset($spacearr[2]) && $spacearr[2]=="PM")
        {
            $hourarr[0]=$hourarr[0]+12;
        }
        return mktime($hourarr[0],$hourarr[1],0,$datearr[1],$datearr[0],$datearr[2]);
    }
}


if(isset($_POST['event_id']) && $_POST['event_id']!='' && isset($_POST['actiontype']) && $_POST['actiontype']=="editeventinfo")
{ 
    $eventinfo=$pdodbobj->fetch_array($pdodbobj->query("select * from af_events where Event_ID=:evtid",array("evtid"=>base64_decode($_POST['event_id']))));
    if(count($eventinfo)>0)
    {
        $_POST['Event']=$eventinfo[0];
    }
}
else
{
    $_POST['Event']=array();
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>AllyFolio | Events </title>
<link href="css/style.css" rel="stylesheet" type="text/css" media="all"  />
<script src="js/general.js"></script>
<script src="js/functions.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href="assets/magicsuggest/magicsuggest-min.css" rel="stylesheet">
<script src="assets/magicsuggest/magicsuggest-min.js"></script>


<link rel="stylesheet" href="alertify/themes/alertify.core.css" />
<link rel="stylesheet" href="alertify/themes/alertify.default.css" id="toggleCSS" />
<script src="alertify/lib/alertify.min.js"></script>	

<script src="js/jquery_raty.js"></script>

<script src="js/jquery_1.9.0.min.js" type="text/javascript"></script>
<script src="assets/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript" src="assets/plugins/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN PAGE LEVEL SCRIPTS -->
<script src="assets/scripts/core/app.js"></script>


<script type="text/javascript">

$(function() {
	
	$('#inlineDatepicker').datepick({
	   format:"mm/dd/YYYY",
       onSelect: showDate  
    });
});

function showDate(date) {
    document.getElementById('eventdate').value=date;
    document.getElementById('actiontype').value='getdateevents';
    document.eventform.action='';
    document.eventform.submit();
}
</script>

<style>
.smalltxt
{
    font-size: 10px;
    font-weight: normal;
    text-align:left; float:left; margin-left:20px;
}
.mediumtxt
{
    font-size: 15px;
    font-weight: normal;
    text-align:left; float:left; margin-left:20px;
}
</style>
<link type="text/css" href="css/jquery.datepick.css" rel="stylesheet">
<script type="text/javascript" src="js/jquery.datepick.js"></script>

</head>


<body>
<div id="main_wrapper">
<?php
    $pageheading="Events";
    require_once("includes/header.php");
    
    $privacytypes=$pdodbobj->fetch_array($pdodbobj->query("select * from af_privacy_types"));
    $clusters=$pdodbobj->fetch_array($pdodbobj->query("select * from af_clusters where Created_By_ID='".$_SESSION['Allyfolio_User_ID']."'"));
    
   ?>
    <!--=================Body Contain Start=======================-->
    <div class="wrapper">
    	<div class="header">
        		<div class="contain-wrap" style="margin-top:30px;">
             		<div class="new_inb3">
            			<form name="eventform" method="post">
                            <ul>
                                <li>
                                    <li>
                        				<div class="creat" >
                        					<span onclick="window.location='events.php';" style="cursor: pointer;">All Events </span>
                        				</div>
                                        <div class="creat">
                        					<span onclick="return getUpcomingEvents();" style="cursor: pointer;">Upcoming Events</span>
                        				</div>
                        				<div class="creat" >
                        					<span onclick="return showhidediv('createeventdiv');" style="cursor: pointer;">Create Events</span>
                        				</div>
                        				
                        				<div class="clearfix"></div>
                				    </li>
                                <div id="upcomingdiv" style="width: 929px;<?php if(isset($_POST['event_id']) && $_POST['event_id']!='' && isset($_POST['actiontype']) && $_POST['actiontype']=="editeventinfo"){ echo "display:none"; } ?>">
                                    <?php
                                    $first_day_of_week = strtotime('monday last week', time());
                                    $last_day_of_week = strtotime('sunday last week', time());
                                    
                                    $eventsidqry="select to_user_id from af_events_settings where user_id=".$_SESSION['Allyfolio_User_ID'];
                                    $eventsidqry1="select user_id from af_events_settings where to_user_id=".$_SESSION['Allyfolio_User_ID'];
                                    
                                    //$query="select af_events.*,Allyfolio_User_ID,Full_Name from af_events,af_users where af_users.User_ID=af_events.Created_By ";
                                    //$query.=" and ( (af_events.Created_By='".$_SESSION['Allyfolio_User_ID']."') or (af_events.Created_By!='".$_SESSION['Allyfolio_User_ID']."' and Event_Status=1)) ";
                                    //$query.=" order by Event_Date asc limit 10";
                                    $birthdayary="SELECT Full_Name ,DOB,Allyfolio_User_ID ,Profile_Pic_Path,User_ID as ltuserid from af_users WHERE
                                                 Activation_Status='Active' AND
                                                (CAST(FROM_UNIXTIME( DOB,  '%d' ) AS SIGNED)>=".date("d",$first_day_of_week)." AND CAST(FROM_UNIXTIME( DOB,  '%m' ) AS SIGNED)>=".date("m",$first_day_of_week)." 
                                                ";
                                    if(date("m",$last_day_of_week)!=date("m",$first_day_of_week))
                                    {
                                        $birthdayary.=" AND CAST(FROM_UNIXTIME( DOB,  '%d' ) AS SIGNED)<=31 AND CAST(FROM_UNIXTIME( DOB,  '%m' ) AS SIGNED)<=".date("m",$first_day_of_week).")
                                                        OR (CAST(FROM_UNIXTIME( DOB,  '%m' ) AS SIGNED)>=".date("m",$last_day_of_week)." AND CAST(FROM_UNIXTIME( DOB,  '%m' ) AS SIGNED)>=1  AND 
                                                         CAST(FROM_UNIXTIME( DOB,  '%d' ) AS SIGNED)<=".date("d",$last_day_of_week)." AND CAST(FROM_UNIXTIME( DOB,  '%m' ) AS SIGNED)<=".date("m",$last_day_of_week).") ";
                                    }
                                    else
                                    {
                                        $birthdayary.=") AND (CAST(FROM_UNIXTIME( DOB,  '%d' ) AS SIGNED)<=".date("d",$last_day_of_week)." AND CAST(FROM_UNIXTIME( DOB,  '%m' ) AS SIGNED)<=".date("m",$last_day_of_week).") ";
                                    }                     
                                    $birthdayary.=" ORDER BY DOB asc";
                                    $eventquery=" SELECT count(Event_ID) as totalevents
                                            FROM af_users,af_events
                                            WHERE af_users.User_ID=af_events.Created_By AND af_users.Activation_Status='Active'
                                            AND af_events.Created_By not in (".$eventsidqry.")
                                            AND af_events.Created_By not in (".$eventsidqry1.") 
                                            AND (
                                                (
                                                af_events.Created_By =  '".$_SESSION['Allyfolio_User_ID']."'
                                                )
                                                OR 
                                                (
                                                af_events.Created_By !=  '".$_SESSION['Allyfolio_User_ID']."'
                                                AND Event_Status =1
                                                )
                                                )
                                            AND (
                                            CASE
                                                WHEN Privacy_Type_ID =2 THEN LOCATE('\'".$_SESSION['Allyfolio_User_ID']."\'',`Active_Friends_IDs` ) 
                                                    OR ".$_SESSION['Allyfolio_User_ID']."=af_events.Created_By
                                                WHEN Privacy_Type_ID =3 THEN LOCATE('\'".$_SESSION['Allyfolio_User_ID']."\'',af_events.Friends_ID ) 
                                                    OR ".$_SESSION['Allyfolio_User_ID']."=af_events.Created_By
                                                WHEN Privacy_Type_ID =4 THEN ".$_SESSION['Allyfolio_User_ID']." = af_events.Created_By OR
                                                    FIND_IN_SET('".$_SESSION['Allyfolio_User_ID']."',af_events.Friends_ID )
                                                ELSE 
                                                        ".$_SESSION['Allyfolio_User_ID']." = af_events.Created_By OR FIND_IN_SET('".$_SESSION['Allyfolio_User_ID']."',Active_Friends_IDs ) OR 
                                                        (Created_By in (select User_ID from af_source_followers where ID_To_Follow=".$_SESSION['Allyfolio_User_ID'].") ) 

                                            END
                                            )
                                            
                                            
                                            ";
                                    if(isset($_POST['eventdate']) && $_POST['eventdate']!="" && isset($_POST['actiontype']) && $_POST['actiontype']=='getdateupcomingevents' )
                                    {
                                        $datearr=explode(" ",$_POST['eventdate']);
                                        
                                        $mindate=mktime(0,0,1,$montharr[strtolower($datearr[1])],$datearr[2],$datearr[3]);
                                        //$maxdate=mktime(23,59,59,$montharr[strtolower($datearr[1])],$datearr[2],$datearr[3]);
                                        $eventquery.=" AND Event_Date>='".$mindate."'";
                                        $eventquery.=" ORDER BY Event_Date asc, DOB asc ";
                                    }
                                    else if(isset($_POST['eventdate']) && $_POST['eventdate']!="" && isset($_POST['actiontype']) && $_POST['actiontype']=='getdateevents' )
                                    {
                                        $datearr=explode(" ",$_POST['eventdate']);
                                        $mindate=mktime(0,0,1,$montharr[strtolower($datearr[1])],$datearr[2],$datearr[3]);
                                        $maxdate=mktime(23,59,59,$montharr[strtolower($datearr[1])],$datearr[2],$datearr[3]);
                                        //$maxdate=mktime(23,59,59,$montharr[strtolower($datearr[1])],$datearr[2],$datearr[3]);
                                        $eventquery.=" AND Event_Date>='".$mindate."' AND Event_Date<='".$maxdate."'";
                                        $eventquery.=" ORDER BY Event_Date asc, DOB asc ";
                                        
                                    }
                                    else
                                    {
                                        //$mindate=mktime(0,0,1,date("m"),date("d"),date("Y"));
                                        //$mindate='1300976001';
                                        //$eventquery.=" AND Event_Date>='".$mindate."' ";
                                        $eventquery.=" ORDER BY Event_Date desc, DOB desc ";
                                    }        
                                    
                                    $eventsinfo=$pdodbobj->fetch_array($pdodbobj->query($eventquery));
                                    if(count($eventsinfo)>0)
                                    {
                                        $totalevents=$eventsinfo[0]['totalevents'];
                                    }
                                    else
                                    {
                                        $totalevents=0;
                                    }
                                    
                                    if(isset($_POST['noofrecords']) && $_POST['noofrecords']>0)
                                    {
                                        $noofrecords=$_POST['noofrecords'];
                                    }
                                    else{
                                        $noofrecords=10;
                                    }
                                    
                                    $eventquery=str_ireplace("count(Event_ID) as totalevents","af_events.*,Allyfolio_User_ID,Full_Name,User_ID",$eventquery);
                                    $eventquery.="  limit 0,".($noofrecords);
                                    $eventsinfo=$pdodbobj->fetch_array($pdodbobj->query($eventquery));
                                    
                                    $birthdayinfo=$pdodbobj->fetch_array($pdodbobj->query($birthdayary));
                                    $currdate=0;
                                    $prevdate=0;
                                    if(count($birthdayinfo)>0)
                                    {
                                        ?>
                                        <li><div class="today">Current Week Birthday Events</div></li>
                                        <?php
                                        for($i=0;$i<count($birthdayinfo);$i++)
                                        {
                                            ?>
                                            <li>
                            				<div class="today_img">
                                                <img src="<?php echo $birthdayinfo[$i]['Profile_Pic_Path']; ?>" width="54" height="48px" />
                                            </div>
                            				<span style="text-align:left; float:left; margin-left:20px;"><?php echo $birthdayinfo[$i]['Full_Name']; ?><p style="font-size:14px;margin-top:10px;">Birthday on <?php echo date("jS, M",$birthdayinfo[$i]['DOB']); ?></p></span>
                            				<div class="clearfix"></div>
                            				
                            				</li>
                                            <?php
                                        }
                                    }
                                    for($i=0;$i<count($eventsinfo);$i++)
                                    {
                                        $currdate=$eventsinfo[$i]['Event_Date'];
                                        if(date("d/m/Y",$currdate)!=date("d/m/Y",$prevdate))
                                        {
                                            ?>
                                            <li><div class="today"><?php if(date("d/m/Y",$currdate)==date("d/m/Y")){ echo "Today"; }else{ echo date("D, d-M-Y",$currdate); } ?></div></li>
                                            <?php
                                            $prevdate=$currdate;
                                        }
                                     
                                        ?>
                        				
                        				<li><div class="today"><span style="text-align:left; float:left; margin-left:20px;"><a href="javascript:void(0);" onclick="return viewEventInfo('<?php echo base64_encode($eventsinfo[$i]['Event_ID']); ?>',<?php if($_SESSION['Allyfolio_User_ID']==$eventsinfo[$i]['Created_By']){ echo "1"; }else{ echo "0"; } ?>)"><?php echo $eventsinfo[$i]['Event_Name']; ?></a></span> <p class="smalltxt" style="padding-top: 10px;"><?php echo "Created By : ".$eventsinfo[$i]['Full_Name']."( ".$eventsinfo[$i]['Allyfolio_User_ID']." )"; ?></p>
                                        <?php if($_SESSION['Allyfolio_User_ID']==$eventsinfo[$i]['Created_By']){ ?><span id="deletespan<?php echo $i; ?>" style="float: right;"><p style="vertical-align: top;width:15px;font-size: 15px;"><a href="javascript:void(0);" style="color: red;" title="Delete Event" onclick="return deleteEvent('<?php echo base64_encode($eventsinfo[$i]['Event_ID']); ?>');">X</a></p></span><?php } ?>
                                        <br /><br />
                                        <p class="mediumtxt" style="text-align:left; float:left; margin-left:20px;"><?php
                                        echo "At : ".$eventsinfo[$i]['Event_Place'];
                                        if($eventsinfo[$i]['Event_Date']>0)
                                            echo "   On : ".date("jS, M Y h:i:s A",$eventsinfo[$i]['Event_Date']);
                                        ?>
                                        </p>
                                        
                        				<div class="clearfix"></div>
                        				</div></li>
                                        <?php
                                        
                                    }
                                    ?>
                    				
                                    <li><div id="inlineDatepicker" style="margin-right:0px; float:right;width:180px;"></div></li>
                    				<div class="clearfix"></div>
                                    <input type="hidden" name="noofrecords" id="noofrecords" value="<?php if(isset($noofrecords) && $noofrecords>0){ echo $noofrecords; }else{ echo "10"; } ?>" />
                    				<?php if($totalevents>$noofrecords){ ?> <li style="text-align:center;"><a href="javascript:void(0);" onclick="return getmoreevents();">More..</a></li><?php } ?>
                                    
                                    <input type="hidden" name="eventdate" id="eventdate" value="<?php if(isset($_POST['eventdate']) && $_POST['eventdate']!=""){ echo $_POST['eventdate']; }else{ echo ""; } ?>" />
                                </div>
                                <div class="createEvent" id="createeventdiv" style="<?php if(!(isset($_POST['event_id']) && $_POST['event_id']!='' && isset($_POST['actiontype']) && $_POST['actiontype']=="editeventinfo")){ ?>display: none; <?php } ?>">
                                
                                <link href="assets/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
                                <link href="assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
                                
                                <link rel="stylesheet" type="text/css" href="assets/plugins/bootstrap-datetimepicker/css/datetimepicker.css"/>
                                    
                                    <?php
                                    if(isset($_POST['Event']['Event_Date']) && $_POST['Event']['Event_Date']!="")
                                    {
                                        $evtdate=date("d/m/Y h:i A",$_POST['Event']['Event_Date']);
                                    }
                                    else
                                    {
                                        $evtdate=date("d/m/Y h:i A");
                                    }
                                    
                                    ?>
                
                                    <label><span>Name</span> <input type="text" name="Event[Event_Name]" id="eventname" placeholder="Event Name" value="<?php if(isset($_POST['Event']['Event_Name'])){ echo trim($_POST['Event']['Event_Name']); } ?>" /></label>
                                    <label><span>Detail</span> <input type="text" name="Event[Detail]" id="details" placeholder="Add More info" value="<?php if(isset($_POST['Event']['Detail'])){ echo trim($_POST['Event']['Detail']); } ?>" /></label>
                                    <label><span>Where</span> <input type="text" name="Event[Event_Place]" id="eventplace" value="<?php if(isset($_POST['Event']['Event_Place'])){ echo trim($_POST['Event']['Event_Place']); } ?>" placeholder="Add a place" /></label>
                                    <label><span>When</span> 
                                        <div class="input-group date form_meridian_datetime">
                						  <input type="text" size="20" style="width: 200px;" name="Event[Event_Date]" id="eventadddate" value="<?php echo $evtdate; ?>" readonly>
                							<button class="btn default date-set" type="button" style="display:none"></button>
                                        </div>
                                    </label>
                                    <label><span>Privacy</span> 
                                        <select name="Event[Privacy_Type_ID]" id="privacy" onchange="return showhideoptions(this.value);">
                                            <option value="">Select Privacy</option>
                                            <?php
                                            for($i=0;$i<count($privacytypes);$i++)
                                            {
                                                ?>
                                                <option value="<?php echo $privacytypes[$i]['ID']; ?>" <?php if((isset($_POST['Event']['Privacy_Type_ID']) && $_POST['Event']['Privacy_Type_ID']==$privacytypes[$i]['ID']) || ($privacytypes[$i]['Privacy_Type_Title']=="Friends" && !isset($_POST['Event']['Privacy_Type_ID']))){ echo "selected"; } ?>  ><?php echo $privacytypes[$i]['Privacy_Type_Title']; ?></option>
                                                <?php
                                            }
                                            ?>
                                        </select>
                                    </label>
                                    <label id="guestinviteid" style="<?php if(isset($_POST['Event']['Privacy_Type_ID']) && !($_POST['Event']['Privacy_Type_ID']==1 || $_POST['Event']['Privacy_Type_ID']==2)){ ?>display: none;<?php } ?>"><span>Guest can Invite friend</span> <input type="radio" value="1" placeholder="" name="Event[Guest_Invite]" id="inviteyes" <?php if(isset($_POST['Event']) && isset($_POST['Event']['Guest_Invite']) && $_POST['Event']['Guest_Invite']=="1"){ echo "Checked"; } ?> />&nbsp;Yes&nbsp;&nbsp;&nbsp;
                                    <input type="radio" placeholder="" name="Event[Guest_Invite]" id="inviteno" value="0" <?php if(isset($_POST['Event']) && isset($_POST['Event']['Guest_Invite']) && $_POST['Event']['Guest_Invite']=="0"){ echo "Checked"; } ?> />&nbsp;No
                                    </label>
                                    
                                    <label id="addfriend" style="<?php if((isset($_POST['Event']['Privacy_Type_ID']) && $_POST['Event']['Privacy_Type_ID']!=3) || !isset($_POST['Event']['Privacy_Type_ID'])){ ?>display: none;<?php } ?>"><span>Add Friend to Invite</span> <input type="text" id="usernames" name="Event[Friends_ID]" placeholder="Type Name" style="margin-left:189px;" /></label>
                                    <label id="cluster" style="<?php if((isset($_POST['Event']['Privacy_Type_ID']) && $_POST['Event']['Privacy_Type_ID']!=4) || !isset($_POST['Event']['Privacy_Type_ID'])){ ?>display: none;<?php } ?>"><span>Invite cluster</span> 
                                        <select name="Event[Cluster_ID]" id="clusterid" >
                                            <option value="">Select Cluster</option>
                                            <?php
                                            for($i=0;$i<count($clusters);$i++)
                                            {
                                                ?>
                                                <option value="<?php echo $clusters[$i]['Cluster_ID']; ?>" <?php if((isset($_POST['Event']['Cluster_ID']) && $_POST['Event']['Cluster_ID']==$clusters[$i]['Cluster_ID'])){ echo "selected"; } ?>  ><?php echo $clusters[$i]['Cluster_Name']; ?></option>
                                                <?php
                                            }
                                            ?>
                                        </select>
                                    </label>
                                    <label><span>Send message to all 
                                    your invited friends</span> <textarea placeholder="Write here....." rows="3" name="Event[Inbox_Message]" id="inboxmessage"><?php if(isset($_POST['Event']['Inbox_Message'])){ echo trim($_POST['Event']['Inbox_Message']); } ?></textarea></label>
                                    <p style="margin-top:40px; text-align:left;"><span><?php if(isset($_POST['event_id']) && $_POST['event_id']!='' && isset($_POST['actiontype']) && $_POST['actiontype']=="editeventinfo"){ ?><input type="submit" value="Delete Event" style="margin-right:40px;" onclick="return deleteEvent('<?php echo $_POST['event_id'] ?>');" /><?php } ?></span> 
                                    <input type="submit" value="<?php if(isset($_POST['event_id']) && $_POST['event_id']!='' && isset($_POST['actiontype']) && $_POST['actiontype']=="editeventinfo"){ echo "Update"; }else{ echo "Create"; } ?>" style="margin-right:40px;" onclick="return checkvalidation();" /> <input type="submit" value="Cancel"  style="margin-right:40px;" onclick="return showhidediv('upcomingdiv');" /> <input type="submit" value="Reset" onclick="return resetall();" />
                                    
                                    </p>
                                    
                                    
                                </div>
                				
                			</ul>
                            <input type="hidden" id="actiontype" name="actiontype" />
                            <input type="hidden" name="event_id" id="event_id" value="<?php if(isset($_POST['event_id'])){ echo $_POST['event_id']; }  ?>" />
            	         </form>
            		</div>
	           </div>
            
            <div class="clearfix"></div>
        </div>
    </div>
     
    <div class="clearfix"></div>
    <!--=================Body Contain end=======================-->
    </div>
    
    <?php
    require_once("includes/footer.php");
?>
<script type="text/javascript">
//<![CDATA[     

var userfriendids="";

function getUpcomingEvents()
{
    document.getElementById('eventdate').value='<?php echo date("D M d Y",time()); ?>';
    document.getElementById('actiontype').value='getdateupcomingevents';
    document.eventform.action='';
    document.eventform.submit();
}

        function viewEventInfo(evtid,flag)
        {
            document.getElementById(['event_id']).value=evtid;
            if(evtid!="")
            {
                if(flag==0)
                {
                    document.eventform.action='event_details.php';
                    document.getElementById('actiontype').value="";
                }
                else
                {
                    document.getElementById('actiontype').value="editeventinfo";    
                }
                
                document.eventform.submit();
            }
        }
        
        function deleteEvent(evtid)
        {
            alertify.confirm("Are you sure, you want to delete the event?", function (e) {
        		if (e) {
        			alertify.success("You've clicked OK");
        			document.getElementById('event_id').value=evtid;
                    document.getElementById('actiontype').value="DeleteEvent";
                    document.eventform.action="";
                    document.eventform.submit();
                    return true;
        		} else {
        			alertify.error("You've clicked Cancel");
                    return false;
        		}
        	});
        	return false;
            
        }
        
        function checkvalidation()
        {
            if(trim(document.getElementById('eventname').value)=="")
            {
                alertify.alert('Please enter the event name');
                document.getElementById('eventname').focus();
                return false;
            }
            else if(trim(document.getElementById('details').value)=="")
            {
                alertify.alert('Please enter the event details');
                document.getElementById('details').focus();
                return false;
            }
            else if(trim(document.getElementById('eventplace').value)=="")
            {
                alertify.alert('Please enter the event place');
                document.getElementById('eventplace').focus();
                return false;
            }
            else if(trim(document.getElementById('eventadddate').value)=="")
            {
                alertify.alert('Please enter the event date');
                document.getElementById('eventadddate').focus();
                return false;
            }
            else if(trim(document.getElementById('privacy').value)=="")
            {
                alertify.alert('Please select the privacy');
                document.getElementById('privacy').focus();
                return false;
            }
            else if(document.getElementById('privacy').value=="1" && !(document.getElementById('inviteyes').checked) && !(document.getElementById('inviteno').checked))
            {
                alertify.alert('Please choose whether guest can invite his/her friend?');
                return false;
            }
            else if(document.getElementById('privacy').value=="2" && !(document.getElementById('inviteyes').checked) && !(document.getElementById('inviteno').checked))
            {
                alertify.alert('Please choose whether guest can invite his/her friend?');
                return false;
            }
            else if(document.getElementById('privacy').value=="3" && trim(userfriendids)=="" && trim(userfriendids)!="[]")
            {
                alertify.alert('Please enter the specific users who are invited');
                return false;
            }
            else if(document.getElementById('privacy').value=="4" && trim(document.getElementById('clusterid').value)=="")
            {
                alertify.alert('Please select the cluster');
                document.getElementById('clusterid').focus();
                return false;
            }
            else if(trim(document.getElementById('inboxmessage').value)=="")
            {
                alertify.alert('Please enter the inbox message');
                document.getElementById('inboxmessage').focus();
                return false;
            }
            else
            {
                /*
                if(document.getElementById('privacy').value==2)
                {
                    document.getElementById('clusterid').value="";
                    document.getElementById('usernames').value="";
                    document.getElementById('inviteyes').checked=false;
                    document.getElementById('inviteno').checked=false;
                }
                */
                
                document.getElementById('actiontype').value="SaveEvent";
                document.getElementById('eventdate').value=""
                
                return true;
            }    
        }   
        
        function resetall()
        {
            document.getElementById('eventname').value='';
            document.getElementById('details').value='';
            document.getElementById('eventplace').value='';
            document.getElementById('eventdate').value='';
            document.getElementById('privacy').value='';
            document.getElementById('inviteyes').value='';
            document.getElementById('inviteno').value='';
            document.getElementById('usernames').value='';
            document.getElementById('clusterid').value='';
            document.getElementById('inboxmessage').value='';
            
            document.getElementById('guestinviteid').style.display='none';
            document.getElementById('addfriend').style.display='none';
            document.getElementById('cluster').style.display='none';
            return false;
        }
        
        $(function() {
            var ms5 = $('#usernames').magicSuggest({
                    width: 300,
                    value: '',
                    id: 'userfriendids',
                    data: 'ajax_search/suggestusers.php' 
                });
                
                 $(ms5).on('selectionchange', function(){
                      userfriendids=JSON.stringify(this.getValue());
                    });
        });
        jQuery(document).ready(function() {   
            
           // initiate layout and plugins
           App.init();
           var handleDatetimePicker = function () {

                $(".form_meridian_datetime").datetimepicker({
                    isRTL: App.isRTL(),
                    format: "dd/mm/yyyy HH:ii P",
                    showMeridian: true,
                    autoclose: true,
                    pickerPosition: (App.isRTL() ? "bottom-right" : "bottom-left"),
                    todayBtn: true,
                    startDate:'<?php echo $evtdate; ?>'
                });
        
                $('body').removeClass("modal-open"); // fix bug when inline picker is used in modal
            }
            
            handleDatetimePicker();
            
            function getjsondata(){
                return 'marilyn@monroe.com,mother@teresa.com,john@kennedy.com,martin@luther.com,nelson@mandela.com,winston@churchill.com,bill@gates.com,muhammad@ali.com,mahatma@gandhi.com,margaret@thatcher.com,charles@gaulle.com,christopher@colombus.com,george@orwell.com,charles@darwin.com,elvis@presley.com,albert@einstein.com,paul@mccartney.com,queen@elizabeth.com,queen@victoria.com,john@keynes.com,mikhail@gorbachev.com,jawaharlal@nehru.com,leonardo@vinci.com,louis@pasteur.com,leo@tolstoy.com,pablo@picasso.com,vincent@gogh.com,franklin@roosevelt.com,john@paul.com,neil@armstrong.com,thomas@edison.com,rosa@parks.com,aung@kyi.com,lyndon@johnson.com,ludwig@beethoven.com,oprah@winfrey.com,indira@gandhi.com,eva@peron.com,benazir@bhutto.com,desmond@tutu.com,dalai@lama.com,walt@disney.com,peter@sellers.com,barack@obama.com,malcolm@x.com,richard@branson.com,jesse@owens.com,ernest@hemingway.com,john@lennon.com,henry@ford.com,haile@selassie.com,joseph@stalin.com,lord@baden.com,michael@jordon.com,george@bush.com,osama@laden.com,fidel@castro.com,oscar@wilde.com,coco@chanel.com,amelia@earhart.com,adolf@hitler.com,mary@magdalene.com,alfred@hitchcock.com,michael@jackson.com,mata@hari.com,emmeline@pankhurst.com,ronald@reagan.com,lionel@messi.com,babe@ruth.com,bob@geldof.com,leon@trotsky.com,roger@federer.com,sigmund@freud.com,woodrow@wilson.com,mao@zedong.com,katherine@hepburn.com,audrey@hepburn.com,david@beckham.com,tiger@woods.com,usain@bolt.com,bill@cosby.com,carl@lewis.com,prince@charles.com,jacqueline@onassis.com,billie@holiday.com,virginia@woolf.com,billie@king.com,kylie@minogue.com,anne@frank.com,emile@zatopek.com,lech@walesa.com,christiano@ronaldo.com,yoko@ono.com,julie@andrews.com,florence@nightingale.com,marie@curie.com,stephen@hawking.com,tim@lee.com,lady@gaga.com,lance@armstrong.com,jon@stewart.com,scarlett@johansson.com,larry@page.com,sergey@brin.com,roman@abramovich.com,rupert@murdoch.com,al@gore.com,sacha@baron.com,george@clooney.com,paul@krugman.com,jimmy@wales.com';
            }
        
        });
        function showhidediv(divid)
        {
            document.getElementById('upcomingdiv').style.display='none';
            document.getElementById('createeventdiv').style.display='none';
            document.getElementById(divid).style.display='';
            return false;
        }
        
        function showhideoptions(optionval)
        {
            if(trim(optionval)!="")
            {
                if(optionval==1 || optionval==2)
                {
                    document.getElementById('guestinviteid').style.display='';
                    document.getElementById('addfriend').style.display='none';
                    document.getElementById('cluster').style.display='none';
                }
                else if(optionval==3)
                {
                    document.getElementById('addfriend').style.display='';
                    document.getElementById('guestinviteid').style.display='none';
                    document.getElementById('cluster').style.display='none';
                }
                else if(optionval==4)
                {
                    document.getElementById('cluster').style.display='';
                    document.getElementById('guestinviteid').style.display='none';
                    document.getElementById('addfriend').style.display='none';
                }
                else
                {
                    document.getElementById('guestinviteid').style.display='none';
                    document.getElementById('addfriend').style.display='none';
                    document.getElementById('cluster').style.display='none';
                }
            
            }
            else
            {
                document.getElementById('guestinviteid').style.display='none';
                document.getElementById('addfriend').style.display='none';
                document.getElementById('cluster').style.display='none';
            }
        }
        
        function getmoreevents()
        {
            document.getElementById('noofrecords').value=parseInt(document.getElementById('noofrecords').value)+10;
            document.getElementById('actiontype').value="getMoreEvents";
            document.eventform.action='';
            document.eventform.submit();
        }
        
        <?php
        if(isset($msg) && $msg!="")
        {
            ?>
            alertify.alert("<?php echo $msg; ?>");
            <?php
            if($actiontype=="SaveEvent" && $msgtype=="Error")
            {
                ?>
                showhidediv('showhidediv');
                
                <?php
            }
            
        }
        ?>
//]]>
</script>